import java.awt.Dimension;

import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTable;

/**
 * Thread that refresh the interface at a given space of time It run in background and so he don't perturb the operation of the interface
 * @author  Jonathan MEISER
 */
public class Refresh extends Thread 
{
	private static final int timeSpace = 3000;
	/**
	 * @uml.property  name="application"
	 * @uml.associationEnd  
	 */
	private ServerInterface application;
	private static final String[] head = {"Users"};
	
	/**
	 * Constructor
	 * @param s  The server interface that must be refreshed
	 */
	public Refresh(ServerInterface s)
	{
		application = s;
	}
	
	/**
	 * Is called when the Thread start
	 * Refresh the interface each 3 seconds (timeSpace)
	 */
	public synchronized void run()
	{
		try
		{
			while(true)
			{
				this.refreshUsers();
				this.refreshMessages();
				application.validate();
				this.wait(timeSpace);  //Wait 3 seconds before a new refresh
			}
		}
		catch (Exception e)
		{
			System.err.println("<Refresh> - An Error is occured : " + e);
			e.printStackTrace();
		}
	}
	
	/**
	 * Refresh the list of all users printed on the server interface
	 */
	private void refreshUsers()
	{
		Object[] connectedUsers = application.getServer().getConnectedUsers();
		Object[] disconnectedUsers = application.getServer().getdisconnectedUsers();
		Object[][] allUsers = new Object[connectedUsers.length+disconnectedUsers.length][1];

		for (int i = 0; i < connectedUsers.length; i++)
		{
			String[] s = connectedUsers[i].toString().split("-");
			allUsers[i][0] = s[1];
		}
		for (int j = 0; j < disconnectedUsers.length; j++)
		{
			String[] s = disconnectedUsers[j].toString().split("-");
			allUsers[connectedUsers.length + j][0] = s[1];
		}
		JTable userTable = new JTable(allUsers, head);
		CellRenderer renderer = new CellRenderer(connectedUsers.length);
		userTable.setDefaultRenderer(Object.class, renderer);
		JScrollPane userList = new JScrollPane(userTable);
		userList.setPreferredSize(new Dimension(170, application.getScreenSize().height-88));
		if (application.getUsers().getComponentCount() > 0)
			application.getUsers().remove(0);
		application.getUsers().add(userList);
	}
	
	/**
	 * Refresh the list of the last messages printed on the server interface
	 */
	private void refreshMessages()
	{
		JList messageList = new JList(application.getServer().getMessages());
		JScrollPane messages = new JScrollPane(messageList);
		messages.setPreferredSize(new Dimension(application.getScreenSize().width-170, application.getScreenSize().height-88));
		if (application.getMessages().getComponentCount() > 0)
			application.getMessages().remove(0);
		application.getMessages().add(messages);
	}
}
